# 资产相关
import json
import os
import re

import time

from autotest import VAR, BASE_DIR

from aw import utils
from aw.utils import excel_util,json_util

sql = VAR.sql
logger = VAR.logger

excel_sheet = None


def getRuleJson(organization="mujing"):
    """获取出规则的json串 organization:机构"""

    config = {
        "mujing":["finance_nova_risk.t_risk_mujin_risk_list_data","finance_nova_risk.t_risk_mujin_risk_list_origin"],
        # "zhongan":["finance_nova_risk.t_risk_zhongan_online_loan","finance_nova_risk.t_risk_zhongan_origin_online_loan"],# 众安网贷
        "zhongan":["`finance_nova_risk`.`t_risk_zhongan_credit_loan`","`finance_nova_risk`.`t_risk_zhongan_origin_credit_loan`"],# 众安信贷
    }

    # 众安网贷
    # name = VAR.name
    # sqlStr1 = 'SELECT * FROM {} WHERE `name` = "{}" ORDER  BY `create_time` DESC LIMIT 1;'.format(config[organization][0],name)

    # 众安信贷
    mobile = VAR.mobile
    sqlStr1 = 'SELECT * FROM {} WHERE `mobile` = "{}" ORDER  BY `create_time` DESC LIMIT 1;'.format(config[organization][0],mobile)

    ret = sql.exec(sqlStr1)
    id = ret[0].get("id")

    sqlStr2 = 'SELECT * FROM {} WHERE `id`={};'.format(config[organization][1],id)

    ret = sql.exec(sqlStr2)

    return json.loads(ret[0].get("content"))


def setRuleJson(ruleJson,organization="mujing"):
    """将规则设置回数据库 organization:机构"""
    config = {
        "mujing":["finance_nova_risk.t_risk_mujin_risk_list_data","finance_nova_risk.t_risk_mujin_risk_list_origin"],
        # "zhongan":["finance_nova_risk.t_risk_zhongan_online_loan","finance_nova_risk.t_risk_zhongan_origin_online_loan"],# 众安网贷
        "zhongan":["`finance_nova_risk`.`t_risk_zhongan_credit_loan`","`finance_nova_risk`.`t_risk_zhongan_origin_credit_loan`"],# 众安信贷
    }

    # 众安网贷
    # name = VAR.name
    # sqlStr1 = 'SELECT * FROM {} WHERE `name` = "{}" ORDER  BY `create_time` DESC LIMIT 1;'.format(config[organization][0],name)

    # 众安信贷
    mobile = VAR.mobile
    sqlStr1 = 'SELECT * FROM {} WHERE `mobile` = "{}" ORDER  BY `create_time` DESC LIMIT 1;'.format(config[organization][0], mobile)

    ret = sql.exec(sqlStr1)
    id = ret[0].get("id")

    ruleJsonStr = json.dumps(ruleJson, ensure_ascii=False)

    sqlStr2 = 'update {} set content = %s WHERE `id`=%s;'.format(config[organization][1])
    sql.exec(sqlStr2, ruleJsonStr, id)

    sqlStr3 = 'SELECT * FROM {} t WHERE t.`id`={};'.format(config[organization][1],id)

    logger.info("规则回填数据库完毕,数据库当前规则如下")
    sql.exec(sqlStr3)


def checkResult(expectVaule, times=1,mode = "SX"):
    """
    检查结果,检查不到结果
    :param expectVaule: 
    :param times:  循环查询 times 次 
    :param mode: 模式. SX 指的是授信  TX指的是提现
    :return: 
    """

    if isinstance(expectVaule,str):
        t = expectVaule.strip().split()
        expectVaule = {"result_code": "D1", "rule_result": "RD", "rule_code": "FDT_ZR00008"}
        expectVaule['rule_code'] = t[0]
        expectVaule['rule_result'] = t[5]
        expectVaule['result_code'] = t[-1]
        print(expectVaule)
        return


    while times > 0:

        name = VAR.name

        if mode == "SX":
            sqlStr1 = 'SELECT * FROM finance_nova_risk.`t_fudai_credit_order` t WHERE t.`name` = "{}" ORDER  BY t.`create_time` DESC LIMIT 1;'.format(
                name)
        else:
            sqlStr1 = 'SELECT * FROM finance_nova_risk.`t_fudai_withdrawal_order` t WHERE t.`user_name` = "{}" ORDER  BY t.`create_time` DESC LIMIT 1;'.format(
                name)

        ret = sql.exec(sqlStr1)
        serial_no = ret[0].get("serial_no")

        sqlStr2 = 'SELECT * FROM finance_nova_risk.`t_risk_rule_result` t WHERE t.`serial_no` = "{}";'.format(serial_no)

        ret = sql.exec(sqlStr2)

        for data in ret:
            if data.get("rule_code") == expectVaule.get("rule_code"):
                if data.get("rule_result") == expectVaule.get("rule_result") and \
                                data.get("result_code") == expectVaule.get("result_code"):
                    logger.info("结果正常,值为:")
                    sql.p.print_list([data.keys(), data.values()])
                    return
        else:
            times -= 1
            logger.info("未查询到,等待后继续查找")
            time.sleep(3)

    raise Exception("出错了,未找到期望的结果")


def getRulesByResolveStr(ruleStr=None):
    """解析字符串,获取规则信息"""

    rules = """
满足以下任一条件时，响应规则
A、身份证命中银行短时逾期风险_时间=A/B，且身份证命中银行短时逾期风险_状态=01/99
B、身份证命中P2P短时逾期风险_时间=A/B，且身份证命中P2P短时逾期风险_状态=01/99
C、身份证命中消费金融短时逾期风险_时间=A/B，且身份证命中消费金融短时逾期风险_状态=01/99
D、身份证命中小贷短时逾期风险_时间=A/B，且身份证命中小贷短时逾期风险_状态=01/99
E、身份证命中商业保险短时逾期风险_时间=A/B，且身份证命中商业保险短时逾期风险_状态=01/99
F、身份证命中非银其他机构短时逾期风险_时间=A/B，且身份证命中非银其他机构短时逾期风险_状态=01/99
    """

    if ruleStr:
        rules = ruleStr

    if "且" in rules:
        pattern = r"\w、(.*?)，且(.*)"
    else:
        pattern = r"\w、(.*?)，?且?(.*)"

    res = []
    for line in rules.strip().split("\n"):
        ret = re.match(pattern, line)
        if ret:
            res1 = ret.group(1)
            res2 = ret.group(2)
            if res1 and res2:
                key1, val1 = strMethod1(res1)
                key2, val2 = strMethod1(res2)
                res.append({key1: val1, key2: val2})
            elif res2:
                key2, val2 = strMethod1(res2)
                res.append({key2: val2})
    logger.info(utils.beauty_json(res))
    return res


def strMethod1(s):
    """将 身份证命中银行短时逾期风险_时间=A/B 处理成"""
    if "<>" in s:
        # 身份证命中银行诈骗风险_状态<>00
        a, b = s.split("<>")
        return a, ["09"]

    a, b = s.split("=")
    if "/" in b:
        c, d = b.split("/")
        return a, [c, d]
    else:
        return a, [b]


def getExcelSheet():
    global excel_sheet

    if not excel_sheet:
        path = os.path.join(BASE_DIR, 'data', '福贷-决策引擎输入输出文档-20190222v3（含规则）.xlsx')
        sheet = excel_util.Sheet(excel_util.WorkBook(path).sheet_by_name("授信节点-输入变量"))
        excel_sheet = sheet

    return excel_sheet


def getConfigByStr(s):
    """根据 身份证命中银行短时逾期风险_时间 这样的字符串从excel中获取出其配置信息"""
    path = os.path.join(BASE_DIR, 'data', '福贷-决策引擎输入输出文档-20190222v3（含规则）.xlsx')
    sheet = excel_util.Sheet(excel_util.WorkBook(path).sheet_by_name("提现节点-输入变量"))

    config = sheet.get_row_by_value(s, col=1)
    logger.info(config)
    return config


def setTestRule(ruleJson, rule):
    """
    设置测试规则
    :param ruleJson: 
    :param rule: [身份证命中P2P短时逾期风险_时间-A,身份证命中P2P短时逾期风险_状态-01]
    :return: 
    """
    if not isinstance(rule,list):
        rule = [rule,]
    logger.info("设置测试规则:{}".format(rule))

    for r in rule:
        # r : 身份证命中P2P短时逾期风险_时间-A
        key, val = r.split("-")
        sheet = getExcelSheet()
        config = excel_util.get_row_by_value(sheet, key, 1)
        setVulueByConfig(config, ruleJson, val)

    logger.info("测试规则设置完毕:{},当前规则\r\n{}".format(rule, ruleJson))


def getTestRules(rule):
    """
    获取测试规则
    :param rule: {'身份证命中P2P短时逾期风险_时间': ['A', 'B'], '身份证命中P2P短时逾期风险_状态': ['01', '99']}
    :return: 拼接成 [
    [身份证命中P2P短时逾期风险_时间-A,身份证命中P2P短时逾期风险_状态-01]
    [身份证命中P2P短时逾期风险_时间-A,身份证命中P2P短时逾期风险_状态-99]
    [身份证命中P2P短时逾期风险_时间-B,身份证命中P2P短时逾期风险_状态-01]
    [身份证命中P2P短时逾期风险_时间-B,身份证命中P2P短时逾期风险_状态-99]
    ]
    """
    keys = list(rule.keys())
    if len(keys) == 2:
        res = []

        k = keys[0]
        s1 = []
        v = rule[k]
        for i in v:
            s1.append("{}-{}".format(k, i))
        # print(s1)

        k = keys[1]
        s2 = []
        v = rule[k]
        for i in v:
            s2.append("{}-{}".format(k, i))
        # print(s2)

        for i in s1:
            for j in s2:
                res.append([i, j])
        return res

    elif len(keys) == 1: # {'身份证命中银行信用不良风险_状态': ['02']}

        k = keys[0]
        s1 = []
        v = rule[k]
        for i in v:
            s1.append("{}-{}".format(k, i))
        return s1

    raise Exception("这错误很奇怪")


def initializeOtherRule(rules, index, ruleJson):
    """
    初始化规则(将其他规则初始化,只保留要测试的规则)
    :param rules: 规则列表
    :param index: 需要保留的规则
    :return: 
    """
    sheet = getExcelSheet()

    # ruleJson = getRuleJson()

    for i,rule in enumerate(rules):
        if i == index:
            continue

        logger.info(rule)
        for key in rule.keys():
            config = excel_util.get_row_by_value(sheet, key, 1)
            setValue = ""

            val = rule[key]
            if len(val) == 1 and val[0] == "09": # {'身份证命中非银其他机构虚假资料风险_状态': ['09']}
                # 将值重置为00
                setValue = "00"

            setVulueByConfig(config, ruleJson,setValue)

    logger.info("规则重置完毕,当前规则为:{}".format(ruleJson))


def setVulueByConfig(config, ruleJson, vaule=""):
    """根据config把该需要置为空的置空"""
    Chinese_name = config.get("变量中文名称")  # id_p2p_bucket_short_time
    english_name = config.get("变量英文名称")  # id_p2p_bucket_short_time
    needed_variable = config.get("所需变量")
    variable_key = english_name[3:].rsplit("_", 1)[0]
    variable_path = needed_variable + "." + variable_key

    # 规则形如: A代表时间,01代表状态
    # "bank_bucket_verysh": {
    #     "self": ["0", "A", "01"]
    # },

    rule = utils.getValueByPath(ruleJson, variable_path)

    if english_name.endswith("time"):
        rule["self"][1] = vaule
    elif english_name.endswith("status"):
        rule["self"][2] = vaule
    else:
        raise Exception("不适用本规则,请检查")

    utils.setValueByPath(ruleJson, rule, variable_path)
    logger.info("{}:{}设置完毕,当前值为:{}".format(Chinese_name, variable_path, utils.getValueByPath(ruleJson, variable_path)))

def writeRule2file(case_name):
    """将json串结果写入文件"""
    ret = getRuleJson("zhongan")
    ret = json_util.beauty_json(ret)

    tmp_path = os.path.join(BASE_DIR,"data","{}.json".format(case_name))
    with open(tmp_path,"w",encoding="utf-8") as f:
        f.write(ret)

    logger.info("json串写入{}完毕".format(tmp_path))


def showRuleVariable(ruleStr):
    """展示规则变量 众安网贷风险查询接口标识=02时，响应规则"""

    signs = ["=",">","<"]
    for sign in signs:
        if sign in ruleStr:
            key = ruleStr.split(sign)[0]
            config = getConfigByStr(key.strip())

            logger.info(json_util.beauty_json(config))

            needed = config.get('所需变量')
            logger.info("所需变量是:{}".format(needed))
            break


def setRule(case_name):
    """将规则设置回数据库"""
    tmp_path = os.path.join(BASE_DIR,"data","{}.json".format(case_name))
    with open(tmp_path,encoding="utf-8") as f:
        ruleJson = json.load(f)
        setRuleJson(ruleJson,organization="zhongan")


if __name__ == '__main__':
    # print(getVariableByStr())
    getConfigByStr("x")
